const {shell} = require('electron')
const linkSection = document.querySelector('.links')
const errorMessage = document.querySelector('.error-message')
const newLinkForm = document.querySelector('.new-link-form')
const newLinkUrl = document.querySelector('.new-link-url')
const newLinkSubmit = document.querySelector('.new-link-submit')
const clearStorageButton = document.querySelector('.clear-storage')

const parser = new DOMParser() // 可解析相应文本的解析器

const getLinks = () => {
  return Object.keys(localStorage)
              .map(item => JSON.parse(localStorage.getItem(item)))
}
const convertToElement = link => {
  return `
    <div class="link">
      <h3>${link.title}</h3>
      <p>
        <a href="${link.url}">${link.url}</a>
      </p>
    </div>
  `
}

const renderList = () => {
  const linkElements = getLinks().map(convertToElement).join('')
  linkSection.innerHTML = linkElements
}

renderList() // 页面初次载入，加载链接

newLinkUrl.addEventListener('keyup', () => {
  newLinkSubmit.disabled = !newLinkUrl.validity.valid
})

clearStorageButton.addEventListener('click', () => {
  window.localStorage.clear()
  renderList()
})

linkSection.addEventListener('click', e => {
  if (e.target.href) {
    e.preventDefault() // 阻止在应用中打开链接
    shell.openExternal(e.target.href) // 在默认浏览器中打开链接
  }
})
const clearForm = () => {
  newLinkUrl.value = null
}

// 错误处理1-非人为造成错误
const validResponce = responce => {
  if (responce.ok) {return responce}
  throw new Error(`Status code of ${responce.status}  ${responce.statusText}`)
}
// 错误处理2-正确的业务，错误的逻辑
const handleError = (error, url) => {
  errorMessage.innerHTML = `
    There was an issue adding "${url}": ${error.message}
  `.trim();
  setTimeout(() => errorMessage.innerHTML = null, 5000)
}
newLinkForm.addEventListener('submit', e => {
  e.preventDefault()
  const url = newLinkUrl.value
  fetch(url)
    .then(validResponce)
    .then(res => {
      return res.text()
    })
    .then(text => {
      return parser.parseFromString(text, 'text/html', 'UTF-8')
    })
    .then(nodes => {
      return nodes.querySelector('title').innerHTML
    })
    .then(title => {
      localStorage.setItem(url, JSON.stringify({title: title, url: url}))
    })
    .then(() => clearForm())
    .then(renderList)
    .catch(err => handleError(err, url))
})

